package com.elias.share.config.bean;

import cn.hutool.core.io.unit.DataSizeUtil;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;


@Data
@Log4j2
@Component
public class FileInfo {
    private final byte[] lock = new byte[0];

    private DataSize usedSize;

    @Value("#{T(org.springframework.util.unit.DataSize).parse('${file.max-size}')}")
    private DataSize maxSize;

    @Value("${file.location}")
    private String location;

    @Value("#{T(java.lang.Integer).valueOf('${file.min-expire-time}')}")
    private Integer minExpireTime;

    @Value("#{T(java.lang.Integer).valueOf('${file.max-expire-time}')}")
    private Integer maxExpireTime;

    public boolean addUsedSize(long fileSize) {
        synchronized (lock) {
            if (usedSize.toBytes() + fileSize > maxSize.toBytes()) {
                return false;
            }
            usedSize = DataSize.ofBytes(usedSize.toBytes() + fileSize);
            return true;
        }
    }

    public void minusUsedSize(long fileSize) {
        synchronized (lock) {
            usedSize = DataSize.ofBytes(usedSize.toBytes() - fileSize);
        }
    }

    @Override
    public String toString() {
        return "FileInfo{" +
                "usedSize=" + DataSizeUtil.format(usedSize.toBytes()) +
                ", maxSize=" + DataSizeUtil.format(maxSize.toBytes()) +
                ", location='" + location + '\'' +
                '}';
    }

}
